import { fetchCartGroupData } from '../../services/cart/cart';
const app = getApp()

Page({
  data: {
    isNotEmpty: false,
    cartGroupData: null,
    totalAmount: 0,
    selectedGoodsCount: 0
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() {
    this.setData({
      cartGroupData: null
    })
    this.getTabBar().init();
    this.refreshData();
  },

  refreshData(content) {
    fetchCartGroupData(app.globalData.userInfo._id).then((res) => {
      let sum = 0;
      res.data.forEach(item=>{
        sum += item.price
      })
      this.setData({ 
        cartGroupData: res.data,
        isNotEmpty: res.data.length > 0,
        totalAmount: sum,
        selectedGoodsCount: res.data.length
      });
      if(content){
        wx.showToast({
          title: content,
          duration: 800
        })
      }
    });
  },
  clearCart(){
    wx.showModal({
      content: '确认清空购物车吗?',
      success: (res)=>{
        if (res.confirm) {
          wx.cloud.database().collection('book-cart').where({
            userid: app.globalData.userInfo._id
          }).remove({
            success:()=>{
              this.setData({
                cartGroupData: null,
                isNotEmpty: false,
                totalAmount: 0,
                selectedGoodsCount: 0
              })
              wx.showToast({
                title: '已清空',
                duration: 500
              })
            }
          })
        }
      }
    })
  },
  goGoodsDetail(e) {
    const { _id } = e.detail.goods;
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${_id}`,
    });
  },

  onGoodsDelete(e) {
    wx.showModal({
      content: '确认删除该商品吗?',
      success : (res)=>{
        if (res.confirm) {
          wx.cloud.database().collection('book-cart').where({
            userid: app.globalData.userInfo._id,
            bookid: e.detail.goods.bookid
          }).remove({
            success:res=>{
              this.refreshData('删除成功')
            }
          })
        }
      }
    })
  },

  onToSettle() {
    wx.setStorageSync('order.goodsRequestList', JSON.stringify(this.data.cartGroupData));
    wx.navigateTo({ url: '/pages/order/order-confirm/index?type=cart' });
  },
  onGotoHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
